package web.User;

import Dao.UserDao;
import com.google.gson.Gson;
import entity.UserBean;
import util.TokenUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String json = "";
        String obj = "";
        resp.setContentType("application/json");
        String userName = req.getParameter("userName").toString();
        String password = req.getParameter("password").toString();
        UserDao userDao = new UserDao();
        UserBean userBeans = userDao.login(userName, password);
        Gson gson = new Gson();
        if(userBeans!=null){
            if(userBeans.getUstate()){
                String token  = TokenUtil.tokenTest(userName,password);
                resp.addHeader("Access-Control-Expose-Headers","token");
                resp.addHeader("token",token);
                boolean isShopowner = false;
                if("店长".equals(userBeans.getRname())){
                    isShopowner = true;
                }
                obj = "{\"msg\":\"验证成功\",\"Uid\":\""+userBeans.getUid()+"\",\"queryFlag\":true,\"isShopowner\":"+isShopowner+"}";
            }else{
                obj = "{\"msg\":\"该账号已被禁用\",\"queryFlag\":false}";
            }
        }else{
            obj = "{\"msg\":\"没有查询到该用户\",\"queryFlag\":false}";
        }
        json = gson.toJson(obj);
        resp.getWriter().println(json);
    }
}
